package com.example.myapplication;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import androidx.appcompat.widget.SwitchCompat;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

/**
 * 添加/编辑禁用时段Activity
 */
public class AddBlockTimeActivity extends AppCompatActivity {

    public static final String EXTRA_BLOCK_TIME_ID = "block_time_id";

    private BlockTimeRepository repository;
    private BlockTimeSlot blockTimeSlot;
    private boolean isEditMode = false;

    // UI组件
    private LinearLayout layoutStartTime;
    private LinearLayout layoutEndTime;
    private LinearLayout layoutRepeat;
    private TextView textStartTime;
    private TextView textEndTime;
    private TextView textRepeatType;
    private SwitchCompat switchSkipHolidays;
    private ImageView btnClose;
    private ImageView btnConfirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_add_block_time);

        repository = new BlockTimeRepository(this);
        
        // 检查是否是编辑模式
        String blockTimeId = getIntent().getStringExtra(EXTRA_BLOCK_TIME_ID);
        if (blockTimeId != null) {
            isEditMode = true;
            blockTimeSlot = repository.getBlockTimeById(blockTimeId);
            if (blockTimeSlot == null) {
                Toast.makeText(this, "未找到时间段", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
        } else {
            blockTimeSlot = new BlockTimeSlot();
            blockTimeSlot.setStartHour(8);
            blockTimeSlot.setStartMinute(0);
            blockTimeSlot.setEndHour(16);
            blockTimeSlot.setEndMinute(30);
            blockTimeSlot.setRepeatType(BlockTimeSlot.RepeatType.DAILY);
        }

        initViews();
        updateUI();
        setupListeners();
    }

    private void initViews() {
        layoutStartTime = findViewById(R.id.layout_start_time);
        layoutEndTime = findViewById(R.id.layout_end_time);
        layoutRepeat = findViewById(R.id.layout_repeat);
        textStartTime = findViewById(R.id.text_start_time);
        textEndTime = findViewById(R.id.text_end_time);
        textRepeatType = findViewById(R.id.text_repeat_type);
        switchSkipHolidays = findViewById(R.id.switch_skip_holidays);
        btnClose = findViewById(R.id.btn_close);
        btnConfirm = findViewById(R.id.btn_confirm);
    }

    private void updateUI() {
        textStartTime.setText(String.format("%02d:%02d", blockTimeSlot.getStartHour(), blockTimeSlot.getStartMinute()));
        textEndTime.setText(String.format("%02d:%02d", blockTimeSlot.getEndHour(), blockTimeSlot.getEndMinute()));
        textRepeatType.setText(blockTimeSlot.getRepeatType().getText());
        switchSkipHolidays.setChecked(blockTimeSlot.isSkipHolidays());
    }

    private void setupListeners() {
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveBlockTime();
            }
        });

        layoutStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog(true);
            }
        });

        layoutEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog(false);
            }
        });

        layoutRepeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRepeatSelectorDialog();
            }
        });

        switchSkipHolidays.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                blockTimeSlot.setSkipHolidays(isChecked);
            }
        });
    }

    private void showTimePickerDialog(final boolean isStartTime) {
        final Dialog dialog = new Dialog(this, R.style.BottomSheetDialog);
        dialog.setContentView(R.layout.dialog_time_picker_scroll);

        TextView title = dialog.findViewById(R.id.text_picker_title);
        title.setText(isStartTime ? "开始时间" : "结束时间");

        final NumberPicker hourPicker = dialog.findViewById(R.id.hour_picker);
        final NumberPicker minutePicker = dialog.findViewById(R.id.minute_picker);

        // 设置小时选择器
        hourPicker.setMinValue(0);
        hourPicker.setMaxValue(23);
        hourPicker.setValue(isStartTime ? blockTimeSlot.getStartHour() : blockTimeSlot.getEndHour());
        hourPicker.setWrapSelectorWheel(true);

        // 设置分钟选择器
        minutePicker.setMinValue(0);
        minutePicker.setMaxValue(59);
        minutePicker.setValue(isStartTime ? blockTimeSlot.getStartMinute() : blockTimeSlot.getEndMinute());
        minutePicker.setWrapSelectorWheel(true);

        dialog.findViewById(R.id.btn_close_picker).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.btn_confirm_time).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int hour = hourPicker.getValue();
                int minute = minutePicker.getValue();

                if (isStartTime) {
                    blockTimeSlot.setStartHour(hour);
                    blockTimeSlot.setStartMinute(minute);
                } else {
                    blockTimeSlot.setEndHour(hour);
                    blockTimeSlot.setEndMinute(minute);
                }

                updateUI();
                dialog.dismiss();
            }
        });

        // 设置对话框位置在底部
        Window window = dialog.getWindow();
        if (window != null) {
            window.setGravity(android.view.Gravity.BOTTOM);
            window.setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT, 
                           android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setBackgroundDrawableResource(android.R.color.transparent);
        }

        dialog.show();
    }

    private void showRepeatSelectorDialog() {
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_repeat_selector);

        RadioGroup radioGroup = dialog.findViewById(R.id.radio_group_repeat);
        RadioButton radioNoRepeat = dialog.findViewById(R.id.radio_no_repeat);
        RadioButton radioDaily = dialog.findViewById(R.id.radio_daily);
        RadioButton radioWorkdays = dialog.findViewById(R.id.radio_workdays);

        // 设置当前选中项
        switch (blockTimeSlot.getRepeatType()) {
            case NO_REPEAT:
                radioNoRepeat.setChecked(true);
                break;
            case DAILY:
                radioDaily.setChecked(true);
                break;
            case WORKDAYS:
                radioWorkdays.setChecked(true);
                break;
        }

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_no_repeat) {
                    blockTimeSlot.setRepeatType(BlockTimeSlot.RepeatType.NO_REPEAT);
                } else if (checkedId == R.id.radio_daily) {
                    blockTimeSlot.setRepeatType(BlockTimeSlot.RepeatType.DAILY);
                } else if (checkedId == R.id.radio_workdays) {
                    blockTimeSlot.setRepeatType(BlockTimeSlot.RepeatType.WORKDAYS);
                }
                updateUI();
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.btn_close_repeat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    private void saveBlockTime() {
        // 验证时间
        int startMinutes = blockTimeSlot.getStartHour() * 60 + blockTimeSlot.getStartMinute();
        int endMinutes = blockTimeSlot.getEndHour() * 60 + blockTimeSlot.getEndMinute();

        if (startMinutes >= endMinutes) {
            Toast.makeText(this, "结束时间必须大于开始时间", Toast.LENGTH_SHORT).show();
            return;
        }

        if (isEditMode) {
            repository.updateBlockTime(blockTimeSlot);
            Toast.makeText(this, "已更新", Toast.LENGTH_SHORT).show();
        } else {
            repository.addBlockTime(blockTimeSlot);
            Toast.makeText(this, "已添加", Toast.LENGTH_SHORT).show();
        }

        finish();
    }
}

